package com.qikecn.utils;

import java.io.File;

import com.qikecn.api.common.Contents;

import cn.geekapp.utils.StringUtils;

/**
 * 临时文件处理类
 * @author wangst
 *
 */
public class FileTempHandleUtil {
	
	/**
	 * 临时文件移动并返回移动后的url地址
	 * @param tempFile
	 * @param relatePath
	 * @param isAddShuiyin
	 * @param logoText
	 * @return
	 */
	public static String moveTempFileAndGetUrl(String tempFile, String relatePath, boolean isAddShuiyin, String logoText){
		if(StringUtils.isEmpty(tempFile)){
			return "";
		}
		if(tempFile.toLowerCase().startsWith("http:") || tempFile.toLowerCase().startsWith("https:")){
			return tempFile;
		}
		String url = "";
		String suffix = FileUtil.getSuffixByFilename(tempFile);
		String saveFilePath = relatePath + FileUtil.getFilenameByDatetime(suffix);
		//boolean flag = true;//FileUtil.moveFile(Contents.ROOT_PATH + Contents.TEMP_PATH + relatePath, Contents.ROOT_PATH + saveFilePath);
		boolean flag = true;
		if(isAddShuiyin && !StringUtils.isEmpty(logoText)){
			flag = true;
			ImageRemarkUtil.markImageByTextInRightBottom(logoText, Contents.ROOT_PATH + Contents.TEMP_PATH + tempFile, Contents.ROOT_PATH + saveFilePath, 0);
			File file = new File(Contents.ROOT_PATH + Contents.TEMP_PATH + tempFile);
			if(file.exists()){
				file.delete();
			}
		}else {
			flag = FileUtil.moveFile(Contents.ROOT_PATH + Contents.TEMP_PATH + tempFile, Contents.ROOT_PATH + saveFilePath);
		}
		if(flag){
			url = Contents.BASE_URL + saveFilePath;
		}
		return url;
	}
	
	/**
	 * 批量处理图片
	 * @param tempFiles 英文逗号隔开
	 * @param relatePath
	 * @param isAddShuiyin
	 * @return
	 */
	public static String handleTempFiles(String tempFiles, String relatePath, boolean isAddShuiyin, String logoText){
		if(StringUtils.isEmpty(tempFiles)){
			return "";
		}
		tempFiles = tempFiles.replaceAll("，", ",");
		tempFiles = tempFiles.replaceAll("[\\,]{2,}", ",");
		String urls = "";
		String[] temps = tempFiles.split(",");
		for(String temp : temps){
			if(!StringUtils.isEmpty(temp)){
				urls += moveTempFileAndGetUrl(temp, relatePath, isAddShuiyin, logoText) + ",";
			}
		}
		urls = urls.replaceAll("[\\,]{2,}", ",");
		if(urls.endsWith(",")){
			urls = urls.substring(0, urls.length() - 1);
		}
		return urls;
	}
}
